//
//  MTClubViewRequestVerifyCell.swift
//  MT
//
//  Created by ooops on 2020/5/13.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import Result

protocol MTRequestVerifyDelegate: NSObjectProtocol {
    /// 同意申请信息
    /// - Parameters:
    ///   - userName: 同意的用户信息
    ///   - eventType: 事件类型1同意加好友，2同意加俱乐部
    ///   - pushId: 群组ID
    func acceptInvitation(userName: String, eventType: Int, pushId: String?)
    /// 拒绝
    func rejectInvitation()
    /// 同意
    func confrimInvitation(userName: String)
}

class MTClubViewRequestVerifyCell: UITableViewCell {
    
    private lazy var userDefaultIcon = UIImage(named: defaultPlaceholderIcon60x60)
    private lazy var provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    var verificationInfo: JCVerificationInfo? {
        didSet {
            if let v = verificationInfo {
                JMSGUser.userInfoArray(withUsernameArray: [v.initiator]) { (result, error) in
                    if error == nil {
                        let users = result as! [JMSGUser]
                        let user = users.first
//                        self.userIconView.mtSetImage(user?.avatar, nil)
                        self.userNickNameLabel.text = user?.displayName()
                    }
                }
                
                /// 入群申请人是自己 不需要显示拒绝和通过的按钮
                let isSelf: Bool = JMSGUser.myInfo().username == v.initiator
                switch v.state {
                case JCVerificationType.wait.rawValue, JCVerificationType.receive.rawValue: /// 发送方等待确认好友申请
                    rejectButton.isHidden = false
                    acceptButton.isHidden = false
                    statusLabel.isHidden = true
                    if isSelf {
                        rejectButton.isHidden = true
                        acceptButton.isHidden = true
                        statusLabel.isHidden = false
                        reciveButton.isHidden = true
                        statusLabel.text = "等待通过审核"
                    }
                case JCVerificationType.accept.rawValue:
                    rejectButton.isHidden = true
                    acceptButton.isHidden = true
                    statusLabel.isHidden = false
                    statusLabel.text = "已通过"
                case JCVerificationType.reject.rawValue:
                    rejectButton.isHidden = true
                    acceptButton.isHidden = true
                    statusLabel.isHidden = false
                    reciveButton.isHidden = true
                    statusLabel.text = "已拒绝"
                default:
                    break
                }
                getInfo(clubId: v.username)
            } else {
                self.userIconView.mtSetImage("", nil)
                self.userNickNameLabel.text = ""
            }
        }
    }
    
    private func getInfo(clubId: String) {
        JMSGGroup.groupInfo(withGroupId: clubId) {[weak self] (result, error) in
            guard let weakSelf = self else { return }
            if error == nil {
                if let g = result as? JMSGGroup {
                    g.thumbAvatarData { (d, s, er) in
                        if let data = d {
                            let image = UIImage(data: data)
                            weakSelf.userIconView.image = image
                        } else {
                            weakSelf.userIconView.image = weakSelf.userDefaultIcon
                        }
                    }
                    weakSelf.descriptionLabel.text = "申请加入 " + (g.name ?? "")
                    //weakSelf.userNickNameLabel.text = weakSelf.verificationInfo?.initiator
                    if let v = weakSelf.verificationInfo, (v.state != JCVerificationType.reject.rawValue && v.state != JCVerificationType.accept.rawValue) {
                        JMSGUser.userInfoArray(withUsernameArray: [v.initiator]) { (result, error) in
                            if error == nil {
                                let users = result as! [JMSGUser]
                                let user = users.first
                                g.memberInfoList({ (result, error) in
                                    if error == nil {
                                        if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                                            let gUsers = userInfos.map { (info) -> JMSGUser? in
                                                return info.user
                                            }
                                            //let isSelf: Bool = JMSGUser.myInfo().username == v.initiator
                                            if gUsers.contains(user) {
                                                //if isSelf {
                                                v.state = 1
                                                JCVerificationInfoDB.shareInstance.insertData(v)
                                                weakSelf.statusLabel.text = "已通过"
                                                //}
                                            }
                                        }
                                    }
                                })
                            }
                        }
                    }
                }
            }
        }
    }
    
    weak var delegate: MTRequestVerifyDelegate?
    
    lazy var userIconView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.cornerRadius = 22
        imageV.layer.borderWidth = 1
        imageV.layer.borderColor = UIColor.black.cgColor
        imageV.layer.masksToBounds = true
        return imageV
    }()
    
    lazy var userNickNameLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "帅气小伙子"
        return l
    }()
    
    lazy var descriptionLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "21岁   西湖区    8km"
        return l
    }()
    
    lazy var msgTipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x9b9b9b
        l.text = "附加留言"
        return l
    }()
    
    lazy var msgLabelBgView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        v.layer.cornerRadius = 4
        return v
    }()
    
    lazy var msgLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCMediumFont(12)
        l.textColor = UIColor.text.x1d1a1a
        //l.text = "f你点接收, 我点你的心"
        l.numberOfLines = 0
        l.preferredMaxLayoutWidth = ScreenWidth - 10 - 10 - 44 - 10
        l.lineBreakMode = .byWordWrapping
        return l
    }()
    
    lazy var rejectButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("拒绝", for: .normal)
        btn.addTarget(self, action: #selector(rejectRequest), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x9b9b9b, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.layer.borderColor = UIColor.text.x9b9b9b.cgColor
        btn.layer.borderWidth = 1
        btn.layer.cornerRadius = 2
        btn.layer.masksToBounds = true
        return btn
    }()
    
    lazy var acceptButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("通过", for: .normal)
        btn.addTarget(self, action: #selector(acceptRequest), for: .touchUpInside)
        btn.setTitleColor(UIColor(hex: 0x29282b), for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.layer.cornerRadius = 2
        btn.layer.masksToBounds = true
        return btn
    }()
    
    lazy var reciveButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("回复", for: .normal)
        btn.addTarget(self, action: #selector(reciveRequest), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(10)
        btn.layer.borderColor = UIColor.text.x1d1a1a.cgColor
        btn.layer.borderWidth = 1
        btn.layer.cornerRadius = 2
        btn.layer.masksToBounds = true
        btn.isHidden = true
        //btn.backgroundColor = UIColor(hex: 0xffc000)
        return btn
    }()
    
    lazy var statusLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(14)
        l.textColor = UIColor.text.x9b9b9b
        l.textAlignment = .right
        l.isHidden = true
        return l
    }()
    
    lazy var giftIconView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.borderColor = UIColor.black.cgColor
        imageV.layer.borderWidth = 1
        return imageV
    }()
    
    lazy var giftsLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(24)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "33"
        return l
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        return v
    }()
    
    class func reuseIdentity() -> String {
        return "MTClubViewRequestVerifyCellID"
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
        makeConstraint()
        self.selectionStyle = .none
    }
    
    private func setupUI() {
        contentView.addSubview(userIconView)
        contentView.addSubview(userNickNameLabel)
        contentView.addSubview(descriptionLabel)
        contentView.addSubview(msgLabelBgView)
        contentView.addSubview(msgTipLabel)
        msgLabelBgView.addSubview(msgLabel)
        msgLabelBgView.addSubview(reciveButton)
        contentView.addSubview(rejectButton)
        contentView.addSubview(acceptButton)
        contentView.addSubview(statusLabel)
        contentView.addSubview(lineView)
    }
    
    private func makeConstraint() {
        
        userIconView.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(10)
            //make.size.equalTo(CGSize(width: 44, height: 44))
            make.width.equalTo(44)
            make.height.equalTo(44)
        }
        
        userNickNameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userIconView.snp.right).offset(10)
            make.bottom.equalTo(userIconView.snp.centerY).offset(-2)
        }
        
        descriptionLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(userIconView.snp.centerY).offset(2)
        }
        
        msgTipLabel.snp.makeConstraints { (make) in
            make.left.equalTo(userIconView)
            //make.top.equalTo(userIconView.snp.bottom).offset(6)
            make.centerY.equalTo(msgLabelBgView)
        }
        
        msgLabelBgView.snp.makeConstraints { (make) in
            make.left.equalTo(userNickNameLabel)
            make.top.equalTo(userIconView.snp.bottom).offset(15)
            make.bottom.equalToSuperview().offset(-20)
            make.right.equalToSuperview().offset(-10)
            make.height.greaterThanOrEqualTo(32)
        }
        
        msgLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(8)
            make.bottom.equalToSuperview().offset(-8)
            make.right.equalTo(rejectButton.snp.left).offset(-10)
        }
        
        rejectButton.snp.makeConstraints { (make) in
            //make.left.equalToSuperview()
            make.right.equalTo(acceptButton.snp.left).offset(-10)
            make.height.equalTo(30)
            make.width.equalTo(56)
            //make.bottom.equalTo(msgLabelBgView.snp.top)
            make.centerY.equalTo(acceptButton)
        }
        
        acceptButton.snp.makeConstraints { (make) in
            make.right.equalTo(msgLabelBgView)
            make.height.equalTo(30)
            make.width.equalTo(56)
            make.bottom.equalTo(msgLabelBgView.snp.top).offset(-17)
        }
        
        reciveButton.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(6)
            make.right.equalToSuperview().offset(-6)
            make.size.equalTo(CGSize(width: 36, height: 20))
        }
        
        statusLabel.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalTo(msgLabelBgView.snp.top).offset(-20)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
    }
    
    @objc private func rejectRequest() {
        guard let info = verificationInfo else { return }
        JMSGUser.userInfoArray(withUsernameArray: [info.initiator]) { (result, error) in
            if error == nil, let users = result as? [JMSGUser], users.count > 0, let u = users.first {
                JMSGGroup.processApplyJoinEventID(info.eventId, gid: info.clubId, join: u, apply: u, isAgree: false, reason: nil) { [weak self] (result, error) in
                    guard let weakSelf = self else { return }
                    if error == nil {
                        weakSelf.rejectButton.isHidden = true
                        weakSelf.acceptButton.isHidden = true
                        weakSelf.statusLabel.isHidden = false
                        weakSelf.statusLabel.text = "已拒绝"
                        weakSelf.reciveButton.isHidden = true
                        info.state = JCVerificationType.reject.rawValue
                        JCVerificationInfoDB.shareInstance.updateData(info)
                    }
                }
            }
        }
    }
    
    @objc private func acceptRequest() {
        guard let info = verificationInfo else { return }
        JMSGUser.userInfoArray(withUsernameArray: [info.initiator]) { (result, error) in
            if error == nil, let users = result as? [JMSGUser], users.count > 0, let u = users.first {
                JMSGGroup.processApplyJoinEventID(info.eventId, gid: info.clubId, join: u, apply: u, isAgree: true, reason: nil) { [weak self] (result, error) in
                    guard let weakSelf = self else { return }
                    if error == nil {
                        weakSelf.rejectButton.isHidden = true
                        weakSelf.acceptButton.isHidden = true
                        weakSelf.statusLabel.text = "已接受"
                        weakSelf.statusLabel.isHidden = false
                        weakSelf.reciveButton.isHidden = true
                        info.state = JCVerificationType.accept.rawValue
                        JCVerificationInfoDB.shareInstance.updateData(info)

                        weakSelf.delegate?.acceptInvitation(userName: info.initiator, eventType: MTRequestVerifyType.group.rawValue, pushId: info.clubId)
                    }
                }
            }
        }
    }
    
    @objc private func reciveRequest() {
        
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
